﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Tools;
using JHStock.Update;
using System.IO;
using Newtonsoft.Json;
using System.Threading;
using JHStock.UserForm;
using System.Text.RegularExpressions;

namespace JHStock
{
    public partial class FormMonit : Form
    {
        public UpdateMonitInfors _umi;
        public StocksLog _stockslog;
        public StocksCustomLog _stockscustomlog;
        public FormLog _formlog;
        public FormCustomLog _formcustomlog;

        public FormMonit(JHConfig _jhconfig, StocksData stocksData)
        {
            InitializeComponent();
            this._jhconfig = _jhconfig;
            this.stocksData = stocksData;
            _ts = null;
            _cfg = new FormMonitConfig();
            _stockslog = new StocksLog(_jhconfig);
            _stockscustomlog = new StocksCustomLog(_jhconfig);
            _formlog = new FormLog(_jhconfig, _stockslog);
            _formcustomlog = new FormCustomLog(_jhconfig, _stockscustomlog);
            _umi = new UpdateMonitInfors();
            StockDraw.Jscfg = _jhconfig.Jsconfig;           
        }
        private void FormMonit_Load(object sender, EventArgs e)
        {
            this.Text = stocksData.KdataType + "-" + _jhconfig.Jsconfig.GetUrlDaysCount(stocksData.KdataType);
            dt = TestStocks.CreateMonitDataTable();
            TestStocks.InitDgvUI(dt, dgv);
        }
        private void buttonConfig_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void buttonSaveLog_Click(object sender, EventArgs e)
        {
            if (_umi.ls.Count == 0) return;
            _stockslog.SaveLog(_umi);
            _stockslog.Save();
        }
        private void ButtonOpenDaily_Click(object sender, EventArgs e)
        {
            _formlog.Show();
        }
        private void buttonCustomLog_Click(object sender, EventArgs e)
        {
            _formcustomlog.Show();
        }
        private void buttonAddToTXDBlock_Click(object sender, EventArgs e)
        {
            ((Button)sender).Enabled = false;
            string str = "";
            foreach (DataGridViewRow dr in dgv.Rows)
            {

                string code = (string)dr.Cells["代码"].Value;
                if (code != null && code.StartsWith("SZ"))
                    str += "\r\n0" + code.Substring(2);
                else if (code != null && code.StartsWith("SH"))
                    str += "\r\n1" + code.Substring(2);
            }

            MFile.WriteAllText( _jhconfig.Jsconfig.pathconfig.BlockPath(), str);
            MessageBox.Show("已输出");
            ((Button)sender).Enabled = true;
        }
        private void buttonToTxt_Click(object sender, EventArgs e)
        {
            string outstr =DataTableTools.DataTableToTxt(dt);
            string filesavename = Tools.TimeStringTools.NowDateMin() + "_Monit" + stocksData.KdataType + ".txt";
            if (checkBoxTable.Checked)
                outstr.Replace(',', '\t');
            MFile.AppendAllText(filesavename, outstr );
            MessageBox.Show("已输出到文件中：" + filesavename);
        }
        private void buttonSaveSelect_Click(object sender, EventArgs e)
        {
            List<DataRow> drs = new List<DataRow>();
            foreach (DataRow dr in dt.Rows)
                if (!(bool)dr["选择"])
                    drs.Add(dr);
            foreach (DataRow dr in drs)
                dt.Rows.Remove(dr);
            _umi.remove(drs);
        }
        private void buttonRefreshMin_Click(object sender, EventArgs e)
        {
            _umi.run("min");
        }
        private void buttonReCompute_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            if(_ts==null && stocksData!=null)
                _ts = new TestStocks(_jhconfig,stocksData);
            _ts.selectstock.Clear();
            _ts.savestockinfor.Clear();

            if (checkBoxUserDefinitionStocks.Checked)
            {
                int days = 0;
                if (!(int.TryParse(textBoxdefineDays.Text, out days) && days > 80))
                    days = 200; //TestStock中   ，int staticdaylenght = 200)
                foreach (Stock s in _jhconfig.Itemshows.StocksByItemsShow())
                   _ts. TestStockSelect(s, !_cfg.ComputeClose,_cfg.MonitOneDay, checkBoxKDate.Checked, checkBoxDebugOutPut.Checked, days);
            }
            else
            {
                foreach (Stock s in _jhconfig.Stocks.stocks)
                   _ts. TestStockSelect(s,!_cfg.ComputeClose, checkBoxKDate.Checked);
            }
            ShowSelectedStocks();
        }
        private void buttonComputeUnImage_Click(object sender, EventArgs e)
        {

        }       
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            _unablebtn = (Button)sender;
            _unablebtn.Enabled = false;
            UpdateStocksData();
            
        }
        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex != -1)
            {
                string numcode = dgv[1, e.RowIndex].Value.ToString().Substring(2, 6);
                Stock s =_jhconfig.Stocks.StockByNumCode(numcode);
                if (s != null && s.Bmp != null)
                {//showImg
                    if (e.ColumnIndex == 5)
                    {
                        FormPictureBox f = new FormPictureBox(s.Bmp);
                        f.ShowDialog();
                    }
                    else if (e.ColumnIndex == 6)
                    {
                        string type = s.Tag.GetType().ToString();
                        FormPictureBox f = new FormPictureBox((Bitmap)s.Tag);
                        f.ShowDialog();

                    }
                    else if (e.ColumnIndex == 1 && checkBoxSHowCWFX.Checked)
                    {
                        FormShow f = new FormShow(s,_jhconfig);
                        f.ShowDialog();

                    }
                }
            }
        }
        
        private void UpdateStocksData()
        {
            if (!_jhconfig.IsUpdate)
            {
                _jhconfig.IsUpdateAllrunning = true;
                System.Threading.Thread nonParameterThread =
                    new Thread(new ThreadStart(ThreadUpdateStocksData));
                nonParameterThread.Start();
            }
        }
        private void ThreadUpdateStocksData()
        {
            string s = stocksData.KdataType;
            TitleMsg = "正在更新" + s + "数据 ";
            _jhconfig.SetKDataType(s);
            stocksData.ThreadShowMsg = ThreadShowMsg;
            stocksData.ActionMsg = ActionMsg;
            string InitDataMsg =  stocksData.InitData();
            TitleMsg = "完成更新" + s + "数据 ";

            ThreadShowMsg(InitDataMsg);
            ThreadCompleteRun();
            _jhconfig.IsUpdateAllrunning = false;
        }
        private void UpdateConfig()
        {
            _cfg.OutGapTxtbyTable = checkBoxTable.Checked;
            _cfg.DetectCustomStocks = checkBoxUserDefinitionStocks.Checked;
            _cfg.DebugOutPut = checkBoxDebugOutPut.Checked;
            _cfg.MonitOneDay = checkBoxMonitdays.Checked;
            _cfg.ComputeClose = radioButtonClos.Checked;
            _cfg.CrossKData = checkBoxKDate.Checked;
            _cfg.ShowCwfx = checkBoxSHowCWFX.Checked;
            _cfg.ShowRoeFiveYears = checkBoxROE5years.Checked;
            _cfg.ShowHexinFromNet = checkBoxShowHexinFromNet.Checked;
        }
        private void ShowSelectedStocks()
        {
            dt.Rows.Clear();
            _umi.Clear();
            int i = 0;
            _umi.b5years = checkBoxROE5years.Checked;
            _umi.bshownet = checkBoxShowHexinFromNet.Checked;
           
            foreach (Stock s in _ts.selectstock)
            {
                DataRow dr = dt.NewRow();
                dr["名称"] = s.Name;
                dr["代码"] = s.Code;
                string[] ss =_ts. savestockinfor[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                if (ss.Length == 3)
                {
                    dr["持续天数"] = ss[0];
                    dr["后续天数"] = ss[1];
                    dr["后续天数的情况"] = ss[2];
                    dr["选择"] = false;
                }
                //if (stocksData..Netdate.Inline)
                {
                    //UpdataOthers( s, ref dr);
                    _umi.Add(s, dr);
                }
                dt.Rows.Add(dr);
                i++;
            }
            if (_ts.selectstock.Count < 80)
                _umi.run(stocksData.KdataType);
        }
        //for thread
        public void ThreadActionMsg(string msg)
        {
            Invoke(new ActionDeleGate(ActionMsg), new object[] { msg });
        }
        public void ActionMsg(string msg)
        {
            if (msg.StartsWith("showexchangingtime-"))
                textBoxExchangeTime.Text = msg.Substring(19);

        }
        private void ThreadShowMsg(string msg)
        {
            this.Invoke(new ShowDeleGate(showfiletxt), new object[] { msg });
        }
        private void ThreadAppendMsg(string msg)
        {
            Invoke(new ShowDeleGate(showappendfiletxt), new object[] { msg });
        }
        private void ThreadCompleteRun()
        {
            Invoke(new CompleteDeleGate(CompleteRun));
        }
        public void CompleteRun()
        {
            if (_unablebtn != null)
                _unablebtn.Enabled = true;
        }
        public void showfiletxt(string file)
        {
            this.textBoxInfor.Text =TitleMsg +  file;
        }
        public void showappendfiletxt(string file)
        {
            this.textBoxInfor.Text += file;
        }

        private JHConfig _jhconfig;
        private StocksData stocksData;
        private FormMonitConfig _cfg;
        private DataTable dt;
        private TestStocks _ts;
        private Button _unablebtn;
        private string TitleMsg;         
    }
    public class FormMonitConfig
    {
        public bool OutGapTxtbyTable { get; set; }
        public bool DetectCustomStocks { get; set; }
        public bool DebugOutPut { get; set; }
        public bool MonitOneDay { get; set; }
        public bool ComputeClose { get; set; }
        public bool CrossKData { get; set; }
        public bool ShowHexinFromNet { get; set; }
        public bool ShowRoeFiveYears { get; set; }
        public bool ShowCwfx { get; set; }
    }
    
    public class UpdateMonitInfors
    {
        public UpdateMonitInfors()
        {
            isruning = false;
            ls = new List<UpdateMonitInfor>();
        }
        public void Clear()
        {
            if (!isruning)
                ls.Clear();
        }
        public void Add(Stock s, DataRow dr)
        {
            if (!isruning)
                ls.Add(new UpdateMonitInfor(this, s, dr, bshownet, b5years));
        }
        public void remove(List<DataRow> drs)
        {
            if (!isruning)
                ls.RemoveAll(r => drs.Contains(r.DataRow()));
        }
        public void run(string type = "none")
        {
            if (!isruning && ls.Count > 0)
            {
                isruning = true;
                this.type = type;
                System.Threading.Thread nonParameterThread = new Thread(new ThreadStart(this.runnet));
                nonParameterThread.Start();
            }
        }
        public void runnet()
        {
            runcount = 0;
            if (type == "none")
            {
                foreach (UpdateMonitInfor u in ls)
                {
                    u.Run();
                }
            }
            else if (type == "min")
            {

                foreach (UpdateMonitInfor u in ls)
                {
                    u.RunMin();
                }
            }
            else if (type == "stocklog")
            {
                foreach (UpdateMonitInfor u in ls)
                {
                    u.RunStockLog();
                }
            }
            else if (type == "dayly")
            {
                foreach (UpdateMonitInfor u in ls)
                {
                    u.RunDayly();
                }
            }
            else if (type == "weekly")
            {
                foreach (UpdateMonitInfor u in ls)
                {
                    u.RunWeekly();
                }
            }
            else if (type == "monthly")
            {
                foreach (UpdateMonitInfor u in ls)
                {
                    u.RunMonthly();
                }
            }
            while (true)
            {
                Thread.Sleep(100);
                if (runcount == 0)
                    break;
            }
            isruning = false;
        }

        public void run(StocksData ActiveStocksData, ColorStyle cs)
        {
            _LocalData = true;
            _ActiveStocksData = ActiveStocksData;
            _cs = cs;
            if (!isruning && ls.Count > 0)
            {
                isruning = true;
                System.Threading.Thread nonParameterThread = new Thread(new ThreadStart(this.runnet1));
                nonParameterThread.Start();
            }
        }
        public void runnet1()
        {
            runcount = 0;
            foreach (UpdateMonitInfor u in ls)
            {
                u.RunLocal(_ActiveStocksData ,_cs);              
            }
            while (true)
            {
                Thread.Sleep(100);
                if (runcount == 0)
                    break;
            }
            isruning = false;
        }

        private string type;
        public bool isruning;
        public int runcount;
        public bool bshownet { get; set; }
        public bool b5years { get; set; }
        public List<UpdateMonitInfor> ls;
        private bool _LocalData;
        private StocksData _ActiveStocksData;
        private ColorStyle _cs;

    }

    public class UpdateMonitInfor
    {
        public UpdateMonitInfor(UpdateMonitInfors ums, Stock s, DataRow dr, bool bShowHexinFromNet, bool bBoxROE5years)
        {
            this.s = s;
            this.dr = dr;
            this.bBoxROE5years = bBoxROE5years;
            this.bShowHexinFromNet = bShowHexinFromNet;
            this.ums = ums;
        }
        public void RunLocal(StocksData _ActiveStocksData, ColorStyle _cs)
        {
            Bitmap bmp = StockDraw.DrawDailyLocal(s, _ActiveStocksData, _cs);
            dr["画图"] = bmp;
        }
        public void Run()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataOthers();
            Interlocked.Decrement(ref ums.runcount);
        }
        public void RunMin()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataMin();
            Interlocked.Decrement(ref ums.runcount);
        }
        public void RunStockLog()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataStockLog();
            Interlocked.Decrement(ref ums.runcount);
        }
        public void RunDayly()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataOthers();
            Interlocked.Decrement(ref ums.runcount);
        }
        public void RunWeekly()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataOthers();
            Interlocked.Decrement(ref ums.runcount);
        }
        public void RunMonthly()
        {
            Interlocked.Increment(ref ums.runcount);
            UpdataMonthly();
            Interlocked.Decrement(ref ums.runcount);
        }
        public DataRow DataRow()
        {
            return dr;
        }
        public static string GetCWXXS(Stock s)
        {
            string html = "";
            string header = "";
            if (true)//bShowHexinFromNet
            {
                string urlt = "http://quote.eastmoney.com/[scode].html";
                string url = urlt.Replace("[scode]", s.Code);
                html = CWeb.GetWebClient(url);
                string pattern = @"(?<=公司核心数据[^-]*)<div class=\""box-x1 mb10\"">[\S\s]*?(?=</table>)";
                html = Regex.Match(html, pattern).Value;
                html = Regex.Replace(html, "<[^<>]*>| ", "");
                html = Regex.Replace(html, "(\r\n){2,}", "\n").Replace("\r\n", "   ").Replace("\n", "\r\n");
                Match m = Regex.Match(html, "(市净率.*)\\r\\n[\\S\\s]*(ROE.* )");
                if (m.Success)
                {
                    header = m.Groups[1].Value + "  " + m.Groups[2] + "\r\n\r\n";
                }
            }
            if (true) //bBoxROE5years
            {
                NetObjectTagstock t = s.Parent.GetTagstock(s.ID);
                if (t != null)
                {
                    List<JsonMainCWFX> ls = JsonConvert.DeserializeObject<List<JsonMainCWFX>>(t.ObjTag.ToString());
                    foreach (JsonMainCWFX js in ls)
                    {
                        header += js.date + "  " + js.jqjzcsyl + "\r\n";
                    }
                    header += "\r\n";
                }
            }
            return header + html;
        }

        private void UpdataStockLog()
        {
            try
            {
                string url = "http://image.sinajs.cn/newchart/daily/n/[stockcode].gif".Replace("[stockcode]", s.Code.ToLower());
                Bitmap bmp = GetBitmapFromUrl(url);
                dr["画图"] = new Bitmap(bmp, bmp.Width / 3, bmp.Height / 3);
                s.Bmp = bmp;
            }
            catch
            {
            }
        }
        private void UpdataMin()
        {
            try
            {
                string url = "http://image.sinajs.cn/newchart/daily/n/[stockcode].gif".Replace("[stockcode]", s.Code.ToLower());
                Bitmap bmp2 = GetBitmapFromUrl(url.Replace("daily", "min"));
                dr["分时图"] = new Bitmap(bmp2, bmp2.Width / 3, bmp2.Height / 3);
                s.Tag = bmp2;
            }
            catch
            {
            }
        }
        private void UpdataOthers()
        {
            try
            {
                string url = "http://image.sinajs.cn/newchart/daily/n/[stockcode].gif".Replace("[stockcode]", s.Code.ToLower());
                Bitmap bmp = GetBitmapFromUrl(url);
                dr["画图"] = new Bitmap(bmp, bmp.Width / 3, bmp.Height / 3);
                Bitmap bmp2 = GetBitmapFromUrl(url.Replace("daily", "min"));
                dr["分时图"] = new Bitmap(bmp2, bmp.Width / 3, bmp.Height / 3);
                s.Bmp = bmp;
                s.Tag = bmp2;
                dr["财务信息"] = GetCWXXS(s);
            }
            catch
            {
            }
        }
        private void UpdataMonthly()
        {
            try
            {
                //string url = "http://image.sinajs.cn/newchart/daily/n/[stockcode].gif".Replace("[stockcode]", s.Code.ToLower());
                //List<KData> kd = s.Parent.StocksData.GetLocalKD(s.ID);
                //Bitmap bmp = s.DrawKData(kd);
                //dr["画图"] = new Bitmap(bmp, bmp.Width / 3, bmp.Height / 3);
                //Bitmap bmp2 = GetBitmapFromUrl(url.Replace("daily", "min"));
                //dr["分时图"] = new Bitmap(bmp2, bmp.Width / 3, bmp.Height / 3);
                //s.Bmp = bmp;
                //s.Tag = bmp2;
                //dr["财务信息"] = GetCWXXS(s);
            }
            catch
            {
            }
        }

        private Bitmap GetBitmapFromUrl(string url)
        {
            //string url = string.Format(@"http://webservice.36wu.com/DimensionalCodeService.asmx/GetCodeImgByString?size={0}&content={1}", 5, 123456);
            System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webres = webreq.GetResponse();
            using (System.IO.Stream stream = webres.GetResponseStream())
            {
                return (Bitmap)Image.FromStream(stream);
            }
        }
        private bool bShowHexinFromNet;
        private bool bBoxROE5years;
        private Stock s;
        private DataRow dr;
        private UpdateMonitInfors ums;
        
    }
}